<template>
  <div class="admin-file-upload">
    <el-row :gutter="20">
      <!-- 左侧：上传区域 -->
      <el-col :span="12">
        <el-card header="文件上传">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="图片上传" name="image">
              <el-upload
                class="upload-demo"
                drag
                :action="imageUploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :on-success="handleImageUploadSuccess"
                :on-error="handleUploadError"
              >
                <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                <div class="el-upload__text">
                  拖拽图片到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 jpg/png/gif/bmp/webp 格式，文件大小不超过 10MB
                  </div>
                </template>
              </el-upload>
              
              <!-- 图片预览 -->
              <div v-if="uploadResult.image" class="upload-result">
                <h4>上传成功</h4>
                <div class="image-preview">
                  <img :src="uploadResult.image.url" :alt="uploadResult.image.name" />
                </div>
                <div class="file-info">
                  <p><strong>文件名:</strong> {{ uploadResult.image.name }}</p>
                  <p><strong>文件大小:</strong> {{ formatFileSize(uploadResult.image.size) }}</p>
                  <p><strong>访问URL:</strong> 
                    <el-input v-model="uploadResult.image.url" readonly>
                      <template #suffix>
                        <el-button type="text" @click="copyUrl(uploadResult.image.url)">
                          <el-icon><CopyDocument /></el-icon>
                        </el-button>
                      </template>
                    </el-input>
                  </p>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="文档上传" name="document">
              <el-upload
                class="upload-demo"
                drag
                :action="documentUploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :before-upload="beforeDocumentUpload"
                :on-success="handleDocumentUploadSuccess"
                :on-error="handleUploadError"
              >
                <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                <div class="el-upload__text">
                  拖拽文档到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 pdf/doc/docx/xls/xlsx/ppt/pptx/txt 格式，文件大小不超过 10MB
                  </div>
                </template>
              </el-upload>

              <!-- 文档信息 -->
              <div v-if="uploadResult.document" class="upload-result">
                <h4>上传成功</h4>
                <div class="document-info">
                  <el-icon class="file-icon"><Document /></el-icon>
                  <div class="file-details">
                    <p><strong>文件名:</strong> {{ uploadResult.document.name }}</p>
                    <p><strong>文件大小:</strong> {{ formatFileSize(uploadResult.document.size) }}</p>
                    <p><strong>文件类型:</strong> {{ uploadResult.document.type }}</p>
                  </div>
                </div>
                <div class="file-info">
                  <p><strong>访问URL:</strong> 
                    <el-input v-model="uploadResult.document.url" readonly>
                      <template #suffix>
                        <el-button type="text" @click="copyUrl(uploadResult.document.url)">
                          <el-icon><CopyDocument /></el-icon>
                        </el-button>
                      </template>
                    </el-input>
                  </p>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="自定义上传" name="custom">
              <div class="custom-upload">
                <el-form :model="customForm" label-width="100px">
                  <el-form-item label="子目录">
                    <el-input v-model="customForm.subDir" placeholder="如: avatars, banners 等" />
                  </el-form-item>
                </el-form>
                
                <el-upload
                  class="upload-demo"
                  drag
                  :action="customUploadUrl"
                  :headers="uploadHeaders"
                  :data="{ subDir: customForm.subDir || 'others' }"
                  :show-file-list="false"
                  :before-upload="beforeCustomUpload"
                  :on-success="handleCustomUploadSuccess"
                  :on-error="handleUploadError"
                >
                  <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                  <div class="el-upload__text">
                    拖拽文件到此处，或<em>点击上传</em>
                  </div>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持图片和文档格式，文件大小不超过 10MB
                    </div>
                  </template>
                </el-upload>

                <!-- 自定义上传结果 -->
                <div v-if="uploadResult.custom" class="upload-result">
                  <h4>上传成功</h4>
                  <div class="file-info">
                    <p><strong>文件名:</strong> {{ uploadResult.custom.name }}</p>
                    <p><strong>文件大小:</strong> {{ uploadResult.custom.sizeFormatted }}</p>
                    <p><strong>文件类型:</strong> {{ uploadResult.custom.type }}</p>
                    <p><strong>访问URL:</strong> 
                      <el-input v-model="uploadResult.custom.url" readonly>
                        <template #suffix>
                          <el-button type="text" @click="copyUrl(uploadResult.custom.url)">
                            <el-icon><CopyDocument /></el-icon>
                          </el-button>
                        </template>
                      </el-input>
                    </p>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>

      <!-- 右侧：操作指南 -->
      <el-col :span="12">
        <el-card header="使用说明">
          <div class="upload-guide">
            <h4>📁 文件上传说明</h4>
            <ul>
              <li><strong>图片上传:</strong> 支持 jpg, png, gif, bmp, webp 格式</li>
              <li><strong>文档上传:</strong> 支持 pdf, doc, docx, xls, xlsx, ppt, pptx, txt 格式</li>
              <li><strong>文件大小:</strong> 单个文件不超过 10MB</li>
              <li><strong>存储目录:</strong> 文件按日期自动分类存储</li>
            </ul>

            <h4>🔗 URL 规则</h4>
            <ul>
              <li>图片文件存储在: <code>/uploads/images/yyyy/MM/dd/</code></li>
              <li>文档文件存储在: <code>/uploads/documents/yyyy/MM/dd/</code></li>
              <li>自定义文件存储在: <code>/uploads/[subDir]/yyyy/MM/dd/</code></li>
            </ul>

            <h4>⚡ 快捷操作</h4>
            <ul>
              <li>点击 📋 按钮可复制文件 URL</li>
              <li>支持拖拽上传，操作更便捷</li>
              <li>上传进度实时显示</li>
            </ul>

            <h4>🗑️ 文件删除</h4>
            <el-form :model="deleteForm" @submit.prevent="handleDeleteFile">
              <el-form-item label="文件路径">
                <el-input 
                  v-model="deleteForm.filePath" 
                  placeholder="请输入要删除的文件路径"
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button type="danger" @click="handleDeleteFile">删除文件</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Document, CopyDocument } from '@element-plus/icons-vue'
import { deleteFile } from '@/api/file'

export default {
  name: 'AdminFileUpload',
  components: {
    UploadFilled,
    Document,
    CopyDocument
  },
  setup() {
    const activeTab = ref('image')
    const uploadResult = reactive({
      image: null,
      document: null,
      custom: null
    })
    
    const customForm = reactive({
      subDir: ''
    })

    const deleteForm = reactive({
      filePath: ''
    })

    // 计算上传URL
    const baseUrl = import.meta.env.VITE_API_BASE_URL || '/api'
    const imageUploadUrl = computed(() => `${baseUrl}/admin/files/upload/image`)
    const documentUploadUrl = computed(() => `${baseUrl}/admin/files/upload/document`)
    const customUploadUrl = computed(() => `${baseUrl}/admin/files/upload`)

    // 上传请求头
    const uploadHeaders = computed(() => {
      const token = localStorage.getItem('access_token')
      return token ? { Authorization: `Bearer ${token}` } : {}
    })

    // 图片上传前验证
    const beforeImageUpload = (file) => {
      const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'].includes(file.type)
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isValidType) {
        ElMessage.error('只能上传 jpg/png/gif/bmp/webp 格式的图片!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('图片大小不能超过 10MB!')
        return false
      }
      
      return true
    }

    // 文档上传前验证
    const beforeDocumentUpload = (file) => {
      const allowedTypes = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'text/plain'
      ]
      
      const isValidType = allowedTypes.includes(file.type)
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isValidType) {
        ElMessage.error('只能上传 pdf/doc/docx/xls/xlsx/ppt/pptx/txt 格式的文档!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('文档大小不能超过 10MB!')
        return false
      }
      
      return true
    }

    // 自定义上传前验证
    const beforeCustomUpload = (file) => {
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isLt10M) {
        ElMessage.error('文件大小不能超过 10MB!')
        return false
      }
      
      return true
    }

    // 图片上传成功
    const handleImageUploadSuccess = (response) => {
      if (response.code === 200) {
        uploadResult.image = response.data
        ElMessage.success('图片上传成功!')
      } else {
        ElMessage.error(response.message || '图片上传失败!')
      }
    }

    // 文档上传成功
    const handleDocumentUploadSuccess = (response) => {
      if (response.code === 200) {
        uploadResult.document = response.data
        ElMessage.success('文档上传成功!')
      } else {
        ElMessage.error(response.message || '文档上传失败!')
      }
    }

    // 自定义上传成功
    const handleCustomUploadSuccess = (response) => {
      if (response.code === 200) {
        uploadResult.custom = response.data
        ElMessage.success('文件上传成功!')
      } else {
        ElMessage.error(response.message || '文件上传失败!')
      }
    }

    // 上传失败
    const handleUploadError = (error) => {
      console.error('上传失败:', error)
      ElMessage.error('文件上传失败!')
    }

    // 复制URL
    const copyUrl = async (url) => {
      try {
        await navigator.clipboard.writeText(url)
        ElMessage.success('URL已复制到剪贴板!')
      } catch (error) {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = url
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        ElMessage.success('URL已复制到剪贴板!')
      }
    }

    // 删除文件
    const handleDeleteFile = async () => {
      if (!deleteForm.filePath) {
        ElMessage.warning('请输入要删除的文件路径')
        return
      }

      try {
        const response = await deleteFile(deleteForm.filePath)
        if (response.code === 200) {
          ElMessage.success('文件删除成功!')
          deleteForm.filePath = ''
        } else {
          ElMessage.error(response.message || '文件删除失败!')
        }
      } catch (error) {
        console.error('删除文件失败:', error)
        ElMessage.error('文件删除失败!')
      }
    }

    // 格式化文件大小
    const formatFileSize = (size) => {
      if (!size) return '-'
      
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(1) + ' KB'
      } else {
        return (size / (1024 * 1024)).toFixed(1) + ' MB'
      }
    }

    return {
      activeTab,
      uploadResult,
      customForm,
      deleteForm,
      imageUploadUrl,
      documentUploadUrl,
      customUploadUrl,
      uploadHeaders,
      beforeImageUpload,
      beforeDocumentUpload,
      beforeCustomUpload,
      handleImageUploadSuccess,
      handleDocumentUploadSuccess,
      handleCustomUploadSuccess,
      handleUploadError,
      copyUrl,
      handleDeleteFile,
      formatFileSize
    }
  }
}
</script>

<style scoped>
.admin-file-upload {
  padding: 20px;
}

.upload-demo {
  margin-bottom: 20px;
}

.upload-result {
  margin-top: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.image-preview {
  margin: 10px 0;
}

.image-preview img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.document-info {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.file-icon {
  font-size: 32px;
  color: #409eff;
  margin-right: 10px;
}

.file-details {
  flex: 1;
}

.file-info {
  margin-top: 10px;
}

.file-info p {
  margin: 5px 0;
  line-height: 1.5;
}

.custom-upload {
  margin-top: 10px;
}

.upload-guide {
  padding: 10px;
}

.upload-guide h4 {
  color: #409eff;
  margin: 15px 0 10px 0;
}

.upload-guide ul {
  margin-left: 20px;
  margin-bottom: 15px;
}

.upload-guide li {
  margin-bottom: 5px;
  line-height: 1.6;
}

.upload-guide code {
  background: #f5f5f5;
  padding: 2px 4px;
  border-radius: 2px;
  font-family: 'Monaco', 'Consolas', monospace;
}
</style>